package demo.controller;

import demo.model.User;
import demo.model.UserDao;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从请求中获取表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 创建用户对象
        User user = new User(username, password);

        UserDao userDao = new UserDao();
        int save = userDao.save(user);

        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println("<html><body>");
        response.getWriter().println("</body></html>");
        if (save > 0) {
            response.getWriter().println("注册成功~");
        } else {
            response.getWriter().println("注册失败~");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("register.jsp");
    }
}
